package org.jmeter.tcp.helmet.gps;

import com.alibaba.fastjson.JSON;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.apache.jorphan.logging.LoggingManager;
import org.apache.log.Logger;

import java.io.*;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

/**
 * @author liangsu
 * @version v1.0
 * @Description
 * @Date 2020/6/29 14:06
 * @since
 */
public class PushGpsUtils {
    protected static final Logger log = LoggingManager.getLoggerForClass();
    private static ScheduledExecutorService scheduledExecutorService;

    static {
        scheduledExecutorService = new ScheduledThreadPoolExecutor(8);
    }

    public void pushGpsDelay(List<Gps> gpsList, String imei, int batchSize) throws IOException, TimeoutException {
        log.info("推送gps总数：" + gpsList.size());

        long now = System.currentTimeMillis();
        long diff = now - gpsList.get(0).getLocationTime().getTime();
        long preTime = now;
        long firstTime = gpsList.get(0).getLocationTime().getTime();

        List<Gps> batchgps = new ArrayList<>(batchSize);
        for (int i = 0; i < gpsList.size(); i++) {
            Gps gps = gpsList.get(i);

            int speed = 1; // 推送速度

            Date time = new Date((gps.getLocationTime().getTime() - firstTime)/speed + firstTime + diff);
            gps.setLocationTime(time);
            gps.setImei(imei);

            try {
                Thread.sleep(time.getTime() - preTime);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            preTime = time.getTime();

            batchgps.add(gps);
            if(i % batchSize == 0 || i == gpsList.size() - 1){
                String str = JSON.toJSONString(batchgps);
//                channel.basicPublish(exchangeName,routingkey, MessageProperties.PERSISTENT_TEXT_PLAIN, str.getBytes());
                System.out.println("当前推送开始"+(i - batchgps.size())+"，共"+batchgps.size()+"条："+str);

                for (Gps batchgp : batchgps) {
                    System.out.println(DateFormatUtils.format(batchgp.getLocationTime(), "yyyy-MM-dd HH:mm:ss"));
                }

                batchgps.clear();
            }
        }

    }

    public static boolean pushGpsDelayWithTask(List<Gps> gpsList, String imei, int batchSize) throws IOException, TimeoutException {
        GpsPushTask gpsPushTask = new GpsPushTask(scheduledExecutorService, imei, gpsList);

        // 增加任务
        boolean success = false;
        if(GpsPushTask.runningTask.putIfAbsent(imei, gpsPushTask) == null){ // 增加任务成功
            success = true;
            log.info("推送gps总数：" + gpsList.size());
            scheduledExecutorService.schedule(gpsPushTask, 0, TimeUnit.MILLISECONDS);
        }

        return success;
    }

    public static boolean pushHttpGpsDelayWithTask(List<Gps> gpsList, String imei, int batchSize,
                                                   String address){
        HttpGpsPushTask gpsPushTask = new HttpGpsPushTask(scheduledExecutorService, imei, gpsList, address);

        // 增加任务
        boolean success = false;
        if(GpsPushTask.runningTask.putIfAbsent(imei, gpsPushTask) == null){ // 增加任务成功
            success = true;
            log.info("推送gps总数：" + gpsList.size());
            scheduledExecutorService.schedule(gpsPushTask, 0, TimeUnit.MILLISECONDS);
        }

        return success;
    }

    public static List<Gps> parseGps(InputStream gpsFileInputStream) throws IOException, TimeoutException, ParseException {
        BufferedReader br = new BufferedReader(new InputStreamReader(gpsFileInputStream));

        String str = br.readLine();

        List<Gps> gpsList = new ArrayList<>(1000);
        while (StringUtils.isNotBlank(str)){
            String[] strs = str.split("\t");
            Gps gps = new Gps();
            gps.setLocationTime(DateUtils.parseDate(strs[0], "yyyy-MM-dd HH:mm:ss"));
            gps.setLng(Double.parseDouble(strs[1]));
            gps.setLat(Double.parseDouble(strs[2]));
            gps.setXs(Double.parseDouble(strs[3]));
            gps.setYs(Double.parseDouble(strs[4]));
            gps.setZs(Double.parseDouble(strs[5]));
            gpsList.add(gps);
            str = br.readLine();
        }

        return gpsList;
    }

}

